#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;

Mat src, gray_img, dst;
int threshold_value = 127;
int threshold_max = 255;
int type_value = 2;
int type_max = 4;
const char* output_title = "binary image";
void Threshold_Demo(int, void*);
int main() {
  src = imread("../images/2.jpg");
  if (src.empty()) {
    cout << "could not load image.." << endl;
    return -1;
  }
  {
    cout << "0:" << THRESH_BINARY << endl;
    cout << "1:" << THRESH_BINARY_INV << endl;
    cout << "2:" << THRESH_TRUNC << endl;
    cout << "3:" << THRESH_TOZERO << endl;
    cout << "4:" << CV_THRESH_TOZERO_INV << endl;
    cout << "7:" << THRESH_MASK << endl;
    cout << "8:" << THRESH_OTSU << endl;
  }
  namedWindow("opencv setup demo", CV_WINDOW_AUTOSIZE);
  imshow("opencv setup demo", src);
  namedWindow(output_title, CV_WINDOW_AUTOSIZE);

  createTrackbar("Threshold Value:", output_title, &threshold_value,
                 threshold_max, Threshold_Demo);

  createTrackbar("Type Value:", output_title, &type_value, type_max,
                 Threshold_Demo);

  Threshold_Demo(0, 0);
  waitKey(0);
  return 0;
}

void Threshold_Demo(int, void*) {
  cvtColor(src, gray_img, CV_BGR2GRAY);
  // threshold(gray_img, dst, threshold_value, threshold_max, THRESH_BINARY);
  // threshold(gray_img, dst, threshold_value, threshold_max,
  // THRESH_BINARY_INV);
  // threshold(gray_img, dst, threshold_value, threshold_max,
  //           THRESH_BINARY | type_value);
  //　自动计算阈值THRESH_OTSU与THRESH_TRIANGLE的图像必须是8位即灰度图
  // threshold(gray_img, dst, 0, 255,
  //           THRESH_OTSU | type_value);
  threshold(gray_img, dst, 0, 255, THRESH_TRIANGLE | type_value);

  imshow(output_title, dst);
}